
class Solution {
public:
    void Next(const string s, int* next)
    {
        int i = 0;
        int j = -1;
        next[i] = j;
        for (i = 1; i < s.size(); ++i)
        {
            while (j >= 0 && s[i] != s[j + 1])
            {
                j = next[j];
            }
            if (s[i] == s[j + 1])
            {
                ++j;
            }
            next[i] = j;
        }
    }
    int strStr(string haystack, string needle) {
        if (needle.size() == 0)
            return 0;
        int next[needle.size()];
        Next(needle, next);
        for (int i = 0, j = -1; i < haystack.size(); ++i)
        {
            while (j >= 0 && haystack[i] != needle[j + 1])
            {
                j = next[j];
            }
            if (haystack[i] == needle[j + 1])
                ++j;
            if (j == (needle.size() - 1))
                return (i - needle.size() + 1);
        }
        return -1;
    }
};